/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mr.qa.UserSessionUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class VerifyCodeServlet extends HttpServlet

{
        private static final Log logger = LogFactory.getLog(VerifyCodeServlet.class);
	private final static Font mFont = new Font("Arial", Font.PLAIN, 11);

        public void init(javax.servlet.ServletConfig servletConfig)
        {
            try
            {
                System.setProperty("java.awt.headless", "true"); 
            }
            catch(Exception e)
            {
                logger.error(e);
            }
        }

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
        {

		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
        {

		String s = "";

		int intCount = 0;

		intCount = (new Random()).nextInt(9999);//

		if (intCount < 1000)
			intCount += 1000;

		s = intCount + "";

		HttpSession session = request.getSession(true);

		session.setAttribute(UserSessionUtil.VerifyCode, s);

		response.setContentType("image/jpg;charset=utf-8");

		ServletOutputStream out = response.getOutputStream();

		BufferedImage image = new BufferedImage(35, 14,
				BufferedImage.TYPE_INT_RGB);

		Graphics gra = image.getGraphics();
		
		//gra.setColor(Color.darkGray);

		gra.fillRect(1, 1, 33, 12);
		
		gra.setColor(Color.black);

		gra.setFont(mFont);

		char c;

		for (int i = 0; i < 4; i++) {

			c = s.charAt(i);

			gra.drawString(c + "", i * 7 + 4, 11);

		}

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		encoder.encode(image);
                out.flush();
		out.close();

	}

}
